package com.danskin.wechat.web;

import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.danskin.wechat.entity.ActivityApply;
import com.danskin.wechat.entity.ActivityApplyConfig;
import com.danskin.wechat.entity.CustActivityApply;
import com.danskin.wechat.entity.VipActivity;
import com.danskin.wechat.entity.VipOption;
import com.danskin.wechat.entity.VipVote;
import com.danskin.wechat.service.ActivityApplyService;
import com.danskin.wechat.service.CustActivityApplyService;
import com.danskin.wechat.service.CustActivityVoteService;
import com.danskin.wechat.service.VipActivityService;
import com.danskin.wechat.service.VipVoteService;
import com.danskin.wechat.util.DateUtils;
import com.danskin.wechat.util.FTPHelper;
import com.danskin.wechat.util.JsonUtils;
import com.danskin.wechat.util.Page;
import com.danskin.wechat.util.Tools;

import net.sf.json.JSONObject;

@Controller
@RequestMapping("activity")
public class CustActivityController extends BaseController{
	
	

	@Autowired
	private VipActivityService activityService;
	
	@Autowired
	private ActivityApplyService activityApplyService;
	
	
	@Autowired
	private VipVoteService vipVoteService;
	
	@Autowired
	private CustActivityVoteService custActivityVoteService;
	
	@Autowired
	private CustActivityApplyService custActivityApplyService;
	 
	
	
	
//==========start==========================投票===========================================//	
	/**
	 * 跳转到投票页面
	 * @return
	 */
	@RequestMapping("/toVotePage")
	public String toVotePage(){
		
		return "activity/vote_list";
	}
	/**
	 * 跳转到投票新增页面
	 * @return
	 */
	@RequestMapping("/toAddVotePage")
	public String toAddVotePage(){
		
		return "activity/add_vote";
	}
	/**
	 * 跳转到投票添加问题页面
	 * @return
	 */
	@RequestMapping("/toAddVoteWt")
	public String toAddVoteWt(Integer account,Model model){
		model.addAttribute("account", account);
		return "activity/add_vote_wt";
	}
	
	/**
	 * 跳转到投票修改页面
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("/toEditVotePage")
	public String toEditVotePage(Integer id,Model model){
		Map<String,Object> param=new HashMap<String, Object>(); 
		VipActivity vipActivity = null;
		if(null!=id){
			vipActivity = activityService.selectVipActivityByPrimaryKey(id);
			
		}
		if(StringUtils.isNotBlank(String.valueOf(vipActivity))){
			model.addAttribute("activity", vipActivity);
			param.put("activityId", vipActivity.getId());
			List<VipVote> list = vipVoteService.selectVipVoteAndVipOptionByActivityId(param);
			if(list.size()>0){
				System.out.println(JsonUtils.objectToJson(list));
				model.addAttribute("voteList", list);
			}
		}
		
		
		
		return "activity/edit_vote";
	}
	/**
	 * 接收投票问题
	 * @return
	 */
	@RequestMapping(value="/doAddVoteWt" , produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String doAddVoteWt(String html,Integer optionX){
		Map<String,Object> map=new HashMap<String, Object>();
		System.out.println(html);
		map.put("status", 200);
		map.put("data", html);
		return JsonUtils.objectToJson(map);
	}
	
	
	
	
	/**
	 * 投票列表展示
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/showActivityVoteList", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object showActivityVoteList(Page page) throws Exception{
		Map map = getRequestParameter(this.getRequest());
		map.put("type", 2);
		map.put("mpId", getLoginUser().getMpId());
		page.setMap(map);
		List<VipActivity> list = activityService.findVipActivityList(page);
		return pagelistToJSONForBootStrapTable(list,page);
	}
	
	/**
	 * 保存投票活动
	 * @param object
	 * @return
	 */
	@RequestMapping(value = "/toSaveActivityVote", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String toSaveActivityVote(@RequestBody JSONObject object){
		Map<String,Object> statusMap=new HashMap<String, Object>();
		VipActivity vipActivity=new VipActivity();
		System.out.println("oragin:"+object);
		int r=0;
		if(object.containsKey("title")){
			if(StringUtils.isNotBlank(object.getString("title"))){
				vipActivity.setTitle(object.getString("title"));
			}
		
		if(object.containsKey("beginTime")){
			if(StringUtils.isNotBlank(object.getString("beginTime"))){
				Date beginTime =(Date) DateUtils.toDate(Date.class,object.get("beginTime"));
				vipActivity.setBeginTime(beginTime);
			}
		}
		if(object.containsKey("endTime")){
			if(StringUtils.isNotBlank(object.getString("endTime"))){
				Date endTime =(Date) DateUtils.toDate(Date.class,object.get("endTime"));
				vipActivity.setEndTime(endTime);
			}
		}
		if(object.containsKey("joinNum")){
			if(StringUtils.isNotBlank(object.getString("joinNum"))){
				vipActivity.setJoinNum(object.getInt("joinNum"));
			}
		}
		vipActivity.setType(new Byte("2"));
		vipActivity.setMpId(this.getMpId());
		vipActivity.setState("0");
	      r = activityService.saveNingActivity(vipActivity);
		}
		
		
		
		
		List<VipVote> vipVoteList=new ArrayList<VipVote>();
		
		if(r>0){
			for(int i=0;i<9;i++){//start  i
				
				if(object.containsKey("type"+(i+1))){
					VipVote vipVote=new VipVote();
					List<VipOption> vipOptionList=new ArrayList<VipOption>();
					vipVote.setType(Byte.valueOf(object.getString("type"+(i+1))));
				
				for(int k=0;k<9;k++){
					
					if(object.containsKey("wt"+(i+1)+"["+k+"]")){//start k
						VipOption option=new VipOption();
						option.setName(object.getString("wt"+(i+1)+"["+k+"]"));
					
					if(object.containsKey("photoCover"+(i+1)+(k+1))){
						option.setImg(object.getString("photoCover"+(i+1)+(k+1)));
					}
					
						vipOptionList.add(option);
					}//end  k
				}
				if(object.containsKey("title"+(i+1))){
					vipVote.setTitle(object.getString("title"+(i+1)));
					
				}
				
					vipVote.setVipOptionList(vipOptionList);
					vipVote.setActivityId(vipActivity.getId());
					vipVoteList.add(vipVote);
				
				}
				
			}//end i
			System.out.println("format:"+JsonUtils.objectToJson(vipVoteList));
			
			try {
				if(null!=vipVoteList){
					for(int z=0;z<vipVoteList.size();z++){
						VipVote vote=vipVoteList.get(z);
						int p=0;
						if(!Tools.isNullOrEmpty(vote)){
							 p= activityApplyService.saveVipVoteSelective(vote);
						}
						
						if(p>0){
							if(null!=vipVoteList.get(z).getVipOptionList()){
								List<VipOption> optionList=vipVoteList.get(z).getVipOptionList();
								for(int q=0;q<optionList.size();q++){
									VipOption option=optionList.get(q);
									if(!Tools.isNullOrEmpty(option)){
										option.setVoteId(vote.getId());
										int fi = activityApplyService.saveVipOptionSelective(option);
									}
								}
								}
							
						}
						
					}
				}
				statusMap.put("status", 200);
				statusMap.put("msg", "新增活动成功");
			} catch (Exception e) {
				statusMap.put("status", 500);
				statusMap.put("msg", e);
				e.printStackTrace();
			}
		}else{
			statusMap.put("status", 500);
			statusMap.put("msg", "新增活动失败——vipActivity");
		}
		
		
		
		return JsonUtils.objectToJson(statusMap);
	}
	
	/**
	 * 修改投票活动
	 * @param object
	 * @return
	 */
	@RequestMapping(value = "/toUpdateActivityVote", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String toUpdateActivityVote(@RequestBody JSONObject object){
		Map<String,Object> statusMap=new HashMap<String, Object>();
		VipActivity vipActivity=new VipActivity();
		System.out.println("oragin:"+object);
		int r=0;
		if(object.containsKey("title")){
			if(StringUtils.isNotBlank(object.getString("title"))){
				vipActivity.setTitle(object.getString("title"));
			}
			
			if(object.containsKey("beginTime")){
				if(StringUtils.isNotBlank(object.getString("beginTime"))){
					Date beginTime =(Date) DateUtils.toDate(Date.class,object.get("beginTime"));
					vipActivity.setBeginTime(beginTime);
				}
			}
			if(object.containsKey("endTime")){
				if(StringUtils.isNotBlank(object.getString("endTime"))){
					Date endTime =(Date) DateUtils.toDate(Date.class,object.get("endTime"));
					vipActivity.setEndTime(endTime);
				}
			}
			if(object.containsKey("joinNum")){
				if(StringUtils.isNotBlank(object.getString("joinNum"))){
					vipActivity.setJoinNum(object.getInt("joinNum"));
				}
			}
			if(object.containsKey("state")){
				if(StringUtils.isNotBlank(object.getString("state"))){
					vipActivity.setState(object.getString("state"));
				}
			}
			if(object.containsKey("id")){
				if(StringUtils.isNotBlank(object.getString("id"))){
					vipActivity.setId(Integer.parseInt(object.getString("id")));
				}
			}
			vipActivity.setType(new Byte("2"));
			vipActivity.setMpId(this.getMpId());
			r = activityService.updateApplyActivity(vipActivity);
		}
		
		
		
		
		List<VipVote> vipVoteList=new ArrayList<VipVote>();
		
		if(r>0){
			for(int i=0;i<9;i++){//start  i
				
				if(object.containsKey("type"+(i+1))){
					VipVote vipVote=new VipVote();
					List<VipOption> vipOptionList=new ArrayList<VipOption>();
					vipVote.setType(Byte.valueOf(object.getString("type"+(i+1))));
					vipVote.setId(object.getInt("id"+(i+1)));
					
					for(int k=0;k<9;k++){
						
						if(object.containsKey("wt"+(i+1)+""+(k+1)+"")){//start k
							VipOption option=new VipOption();
							option.setName(object.getString("wt"+(i+1)+""+(k+1)+""));
							option.setId(object.getInt("id"+(i+1)+""+(k+1)+""));
							
							if(object.containsKey("photoCover"+(i+1)+(k+1))){
								option.setImg(object.getString("photoCover"+(i+1)+(k+1)));
							}
							
							vipOptionList.add(option);
						}//end  k
					}
					if(object.containsKey("title"+(i+1))){
						vipVote.setTitle(object.getString("title"+(i+1)));
						
					}
					
					vipVote.setVipOptionList(vipOptionList);
					vipVote.setActivityId(vipActivity.getId());
					vipVoteList.add(vipVote);
					
				}
				
			}//end i
			System.out.println("format:"+JsonUtils.objectToJson(vipVoteList));
			
			try {
				if(null!=vipVoteList){
					for(int z=0;z<vipVoteList.size();z++){
						VipVote vote=vipVoteList.get(z);
						int p=0;
						if(!Tools.isNullOrEmpty(vote)){
							p= activityApplyService.updateVipVoteSelective(vote);
						}
						
						if(p>0){
							if(null!=vipVoteList.get(z).getVipOptionList()){
								List<VipOption> optionList=vipVoteList.get(z).getVipOptionList();
								for(int q=0;q<optionList.size();q++){
									VipOption option=optionList.get(q);
									if(!Tools.isNullOrEmpty(option)){
										option.setVoteId(vote.getId());
										int fi = activityApplyService.updateVipOptionSelective(option);
									}
								}
							}
							
						}
						
					}
				}
				statusMap.put("status", 200);
				statusMap.put("msg", "新增活动成功");
			} catch (Exception e) {
				statusMap.put("status", 500);
				statusMap.put("msg", e);
				e.printStackTrace();
			}
		}else{
			statusMap.put("status", 500);
			statusMap.put("msg", "新增活动失败——vipActivity");
		}
		
		
		
		return JsonUtils.objectToJson(statusMap);
	}
	
	
	
	/**
	 * 投票图片上传
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/voteFileUpload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public String fileUpload(@RequestParam(name="lefile1",required=false) MultipartFile file,
	@RequestParam(name="lefile2",required=false) MultipartFile file2,@RequestParam(name="lefile3",required=false) MultipartFile file3,	
	@RequestParam(name="lefile4",required=false) MultipartFile file4,@RequestParam(name="lefile5",required=false) MultipartFile file5,
	@RequestParam(name="lefile6",required=false) MultipartFile file6,@RequestParam(name="lefile7",required=false) MultipartFile file7,
	@RequestParam(name="lefile8",required=false) MultipartFile file8,@RequestParam(name="lefile9",required=false) MultipartFile file9
			) throws Exception {
		 FTPHelper.getInstance();
			Map<String,Object> map=new HashMap<String, Object>();
			String pictureUrl = null;
		
			if(null!=file){
				pictureUrl=  FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(file, "vote",
						 FTPHelper.uploadTemporaryFile("1"));
			}
			if(null!=file2){
				pictureUrl=  FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(file2, "vote",
						 FTPHelper.uploadTemporaryFile("2"));
			}
			if(null!=file3){
				pictureUrl=  FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(file3, "vote",
						 FTPHelper.uploadTemporaryFile("3"));
			}
			if(null!=file4){
				pictureUrl=  FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(file4, "vote",
						 FTPHelper.uploadTemporaryFile("4"));
			}
			if(null!=file5){
				pictureUrl=  FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(file5, "vote",
						 FTPHelper.uploadTemporaryFile("5"));
			}
			if(null!=file6){
				pictureUrl=  FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(file6, "vote",
						 FTPHelper.uploadTemporaryFile("6"));
			}
			if(null!=file7){
				pictureUrl=  FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(file7, "vote",
						 FTPHelper.uploadTemporaryFile("7"));
			}
			if(null!=file8){
				pictureUrl=  FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(file8, "vote",
						 FTPHelper.uploadTemporaryFile("8"));
			}
			if(null!=file9){
				pictureUrl=  FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(file9, "vote",
						 FTPHelper.uploadTemporaryFile("9"));
			}
			if(null!=pictureUrl){
				map.put("status", 200);
				map.put("data", pictureUrl);
			}else{
				map.put("status", 400);
				map.put("data", "");
			}
			return  JsonUtils.objectToJson(map);
	}
	/**
	 * 投票图片修改
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@ResponseBody
	@RequestMapping(value = "/voteEditFileUpload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public String fileUpload(HttpServletRequest request) throws Exception {
		
		List<MultipartFile> list = getMultipartFileList(request);
		System.out.println(list.size());
		
		Map<String,Object> map=new HashMap<String, Object>();
		String pictureUrl = null;
		
		if(list.size()>0){
			MultipartFile file=list.get(0);
			pictureUrl=  FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(file, "vote",
					FTPHelper.uploadTemporaryFile("1"));
		}
		if(null!=pictureUrl){
			map.put("status", 200);
			map.put("data", pictureUrl);
		}else{
			map.put("status", 400);
			map.put("data", "");
		}
		return  JsonUtils.objectToJson(map);
	}
	
	/** 
     * 获取当前请求中的文件列表 
     *  
     * @param request 
     * @return 
     */  
    protected List<MultipartFile> getMultipartFileList(  
            HttpServletRequest request) {  
        List<MultipartFile> files = new ArrayList<MultipartFile>();  
        try {  
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(  
                    request.getSession().getServletContext());  
            if (request instanceof MultipartHttpServletRequest) {  
                // 将request变成多部分request  
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;  
                Iterator<String> iter = multiRequest.getFileNames();  
                // 检查form中是否有enctype="multipart/form-data"  
                if (multipartResolver.isMultipart(request) && iter.hasNext()) {  
                    // 获取multiRequest 中所有的文件名  
                    while (iter.hasNext()) {  
                        // 一次遍历所有文件  
                        // MultipartFile file =  
                        // multiRequest.getFile(iter.next().toString());  
                        // if (file != null) {  
                        // files.add(file);  
                        // }  
                        // 适配名字重复的文件  
                        List<MultipartFile> fileRows = multiRequest  
                                .getFiles(iter.next().toString());  
                        if (fileRows != null && fileRows.size() != 0) {  
                            for (MultipartFile file : fileRows) {  
                                if (file != null && !file.isEmpty()) {  
                                    files.add(file);  
                                }  
                            }  
                        }  
                    }  
                }  
            }  
        } catch (Exception ex) {  
            ex.printStackTrace();
        }  
        return files;  
    } 
	/**
	 * 删除投票活动
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/toDeleteActivityVote", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String toDeleteActivityVote(Integer id){
		Map<String,Object> map=new HashMap<String, Object>();
		
		int i=activityService.deleteVipActivity(id);
		if(i>0){
			map.put("status", 200);
			map.put("msg", "删除成功");
		}else{
			map.put("status", 400);
			map.put("msg", "删除失败");
		}
		return JsonUtils.objectToJson(map);
	}
//----------------end---------------------------投票活动------------------------------------------------------------//	

	
//--------------start------------------------凝聚日------------------------------------------------------------//

	@RequestMapping("/toNingPage")
	public String toNingPage(){
		
		return "activity/ning_list";
	}
	
	/**
	 * 投票列表展示
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/showActivityNingList", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object showActivityNingList(Page page) throws Exception{
		Map map = getRequestParameter(this.getRequest());
		map.put("type", 3);
		map.put("mpId", getLoginUser().getMpId());
		page.setMap(map);
		List<VipActivity> list = activityService.findVipActivityList(page);
		return pagelistToJSONForBootStrapTable(list,page);
	}
	
	/**
	 * 跳转到宁聚日新增页面
	 * @return
	 */
	@RequestMapping("/toAddNingPage")
	public String toAddNingPage(){
		
		return "activity/add_ning";
	}
	/**
	 * 跳转到修改凝聚日页面
	 * @return
	 */
	@RequestMapping("/toEditNingPage")
	public String toEditNingPage(Integer id,Model model){
		if(null!=id){
			VipActivity activity = activityService.selectVipActivityByPrimaryKey(id);
			model.addAttribute("ning", activity);
		}
		
		return "activity/edit_ning";
	}
	/**
	 * 凝聚日新增
	 * @param activity
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="/toSaveActivityNing", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String toSaveActivityNing(@RequestBody Map<String,Object> param) throws Exception{
		Map<String,Object> map=new HashMap<String, Object>();
		Date beginTime = (Date)DateUtils.toDate(Date.class,param.get("beginTime"));
		Date endTime =(Date) DateUtils.toDate(Date.class,param.get("endTime"));
		param.remove("beginTime");
		param.remove("endTime");
		VipActivity vipActivity = Tools.toBean(param, VipActivity.class);
		vipActivity.setBeginTime(beginTime);
		vipActivity.setEndTime(endTime);
		vipActivity.setType(new Byte("3"));
		vipActivity.setState("0");
		vipActivity.setMpId(this.getMpId());
		int i = activityService.saveNingActivity(vipActivity);
		if(i>0){
			map.put("status", 200);
			map.put("msg", "新增凝聚日成功");
		}else{
			map.put("status", 400);
			map.put("msg", "新增凝聚日失败");
		}
		return JsonUtils.objectToJson(map);
	}
	@RequestMapping(value="/toUpdateActivityNing", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String toUpdateActivityNing(@RequestBody Map<String,Object> param) throws Exception{
		Map<String,Object> map=new HashMap<String, Object>();
		Date beginTime = (Date)DateUtils.toDate(Date.class,param.get("beginTime"));
		Date endTime =(Date) DateUtils.toDate(Date.class,param.get("endTime"));
		param.remove("beginTime");
		param.remove("endTime");
		VipActivity vipActivity = Tools.toBean(param, VipActivity.class);
		vipActivity.setBeginTime(beginTime);
		vipActivity.setEndTime(endTime);
		int i = activityService.updateApplyActivity(vipActivity);
		if(i>0){
			map.put("status", 200);
			map.put("msg", "修改凝聚日成功");
		}else{
			map.put("status", 400);
			map.put("msg", "修改凝聚日失败");
		}
		return JsonUtils.objectToJson(map);
	}
	
	@ResponseBody
	@RequestMapping(value = "/ningFileUpload", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
	public String ningFileUpload(@RequestParam(name="picture",required=false) MultipartFile file
			) throws Exception {
		 FTPHelper.getInstance();
			Map<String,Object> map=new HashMap<String, Object>();
			String pictureUrl = null;
		
			if(null!=file){
				pictureUrl=  FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(file, "ning",
						 FTPHelper.uploadTemporaryFile("1"));
			}
			if(null!=pictureUrl){
				map.put("status", 200);
				map.put("data", pictureUrl);
			}else{
				map.put("status", 400);
				map.put("data", "");
			}
			return  JsonUtils.objectToJson(map);
	}
	//-------------------end------------------------宁聚日----------------------------------------------//
	
	
	//-------------------start------------------------报名----------------------------------------------//
	/**
	 * 跳转到报名页面
	 * @return
	 */
	@RequestMapping("/toApplyPage")
	public String toApplyPage(){
		
		return "activity/apply_list";
	}
	/**
	 * 跳转到新增报名页面
	 * @return
	 */
	@RequestMapping("/toAddApplyPage")
	public String toAddApplyPage(Model model){
		List<ActivityApplyConfig> list = activityApplyService.getAllActivityApplyConfig();
		model.addAttribute("tag", list);
		return "activity/add_apply";
	}
	/**
	 * 跳转到修改报名页面
	 * @return
	 */
	@RequestMapping("/toEditApplyPage")
	public String toEditApplyPage(String id,Model model){
		VipActivity vipActivity = activityService.findVipActivitybyId(id);
		List<ActivityApply> list = activityApplyService.findactivityApply(id);
		model.addAttribute("apply",vipActivity);
		model.addAttribute("tag", list);
		return "activity/edit_apply";
	}
	
	
	
	/**
	 * 投票报名展示
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/showActivityApplyList", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object showActivityApplyList(Page page) throws Exception{
		Map map = getRequestParameter(this.getRequest());
		map.put("type", 1);
		map.put("mpId", getLoginUser().getMpId());
		page.setMap(map);
		List<VipActivity> list = activityService.findVipActivityList(page);
		return pagelistToJSONForBootStrapTable(list,page);
	}
	
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/toSaveActivityApply", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String toSaveActivityApply(@RequestBody Map<String,Object> param,HttpServletRequest request) throws Exception{
		Map<String,Object> map=new HashMap<String, Object>();
		List<File>  files=null;
		String details=(String)param.get("details");
		if(StringUtils.isNotBlank(details)){
			files= this.getPathImg(details,request);
		}
		
		List<String>  tag=new ArrayList<String>();
		if(param.containsKey("tag")){
			tag=(List<String>)param.get("tag");
			param.remove("tag");
		}
		
		String regex = "src=\"(.*?)\"";
		String detail=null;
		String[] split=null;
		if(StringUtils.isNotBlank(details)){
			split= details.split(regex);
			if(split.length>0){
				detail=split[0];
			}
		}
		
		try {
			String[] pictureUrl=new String[files.size()];
				for(int i=0;i<files.size();i++){
					int k=i+1;
					FileInputStream input = new FileInputStream(files.get(i)); 
			    	MultipartFile multipartFile = new MockMultipartFile("file", files.get(i).getName(), "text/plain", IOUtils.toByteArray(input));
					pictureUrl[i]=  FTPHelper.getInstance().uploadPictureAndReturnPictureUrl(multipartFile, "apply",
							files.get(i).getCanonicalPath().substring(0, (files.get(i).getCanonicalPath().lastIndexOf(File.separator))));
					detail+="src=\""+pictureUrl[i]+"\""+split[k];
				}
			param.put("description", detail);
		} catch (Exception e) {
			param.put("description", details);
		}
		
	
		
		Date beginTime =(Date) DateUtils.toDate(Date.class,param.get("beginTime"));
		Date endTime =(Date) DateUtils.toDate(Date.class,param.get("endTime"));
		param.remove("beginTime");
		param.remove("endTime");
		
		VipActivity vipActivity = Tools.toBean(param, VipActivity.class);
		vipActivity.setBeginTime(beginTime);
		vipActivity.setEndTime(endTime);
		vipActivity.setType(new Byte("1"));
		vipActivity.setState("0");
		vipActivity.setMpId(this.getMpId());
		int i = activityService.saveNingActivity(vipActivity);
		if(tag.size()>0){
			for(int k=0;k<tag.size();k++){
				ActivityApply apply=new ActivityApply();
				apply.setActivityId(vipActivity.getId());
				apply.setApplyConfigCode(tag.get(k));
				apply.setApplyConfigName(tag.get(k));
				activityApplyService.saveActivityApply(apply);
			}
		}
		if(i>0){
			map.put("status", 200);
			map.put("msg", "新增报名成功");
		}else{
			map.put("status", 400);
			map.put("msg", "新增报名失败");
		}
		return JsonUtils.objectToJson(map);
	}
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/toUpdateActivityApply", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public String toUpdateActivityApply(@RequestBody Map<String,Object> param,HttpServletRequest request) throws Exception{
		Map<String,Object> map=new HashMap<String, Object>();
		List<String>  tag=new ArrayList<String>();
		if(param.containsKey("tag")){
			tag=(List<String>)param.get("tag");
			param.remove("tag");
		}
		
		Date beginTime =(Date) DateUtils.toDate(Date.class,param.get("beginTime"));
		Date endTime =(Date) DateUtils.toDate(Date.class,param.get("endTime"));
		param.remove("beginTime");
		param.remove("endTime");
		VipActivity vipActivity = Tools.toBean(param, VipActivity.class);
		vipActivity.setBeginTime(beginTime);
		vipActivity.setEndTime(endTime);
		System.out.println(vipActivity);
		int i = activityService.updateApplyActivity(vipActivity);
		
		if(tag.size()>0){
			activityApplyService.deleteVipApplyByActivityId(vipActivity.getId());
			for(int k=0;k<tag.size();k++){
				ActivityApply apply=new ActivityApply();
				apply.setActivityId(vipActivity.getId());
				apply.setApplyConfigCode(tag.get(k));
				apply.setApplyConfigName(tag.get(k));
				activityApplyService.saveActivityApply(apply);
			}
		}
		
		if(i>0){
			map.put("status", 200);
			map.put("msg", "修改报名成功");
		}else{
			map.put("status", 400);
			map.put("msg", "修改报名失败");
		}
		return JsonUtils.objectToJson(map);
		
	}
	//-----------end-----------------------报名活动------------------------------------------------//
	
	//------------start-----------------------投票统计开始------------------------------------------------//
	
	/**
	 * 跳转到投票统计页面
	 * @return
	 */
	@RequestMapping("/toVoteStaticPage")
	public String toVoteStaticPage(){
		
		return "activity/vote_static_list";
	}
	
	/**
	 * 投票统计表格展示
	 * @param page
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/showVoteActivityStaticList", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object showVoteActivityStaticList(Page page) throws Exception{
		Map map = getRequestParameter(this.getRequest());
		map.put("type", 2);
		map.put("mpId", getLoginUser().getMpId());
		page.setMap(map);
		List<Map<String,Object>> list = custActivityVoteService.listPageActivityVoteStatic(page);
		return pagelistToJSONForBootStrapTable(list,page);
	}
	
	/**
	 * 删除投票统计记录
	 */
	@RequestMapping("/toDeleteActivityVoteStatic")
	@ResponseBody
	public String toDeleteActivityVoteStatic(Integer id){
		Map<String,Object> map=new HashMap<String, Object>();
		int i=0;
		if(null!=id){
			i = custActivityVoteService.deleteCustActivityVoteStatic(id);
		}
		if(i>0){
			map.put("status", 200);
			map.put("msg", "删除投票活动统计成功");
		}else{
			map.put("status", 400);
			map.put("msg", "删除投票活动统计失败");
		}
		return JsonUtils.objectToJson(map);
	}
	
	
	
//------------------------start-------报名统计页面--------------------------------------------//
	
	
	
	
	
	@RequestMapping("/toApplyStaticPage")
	public String toApplyStaticPage(){
		
		return "activity/apply_static_list";
	}
	
	
	@RequestMapping(value = "/showApplyActivityStaticList", produces = "application/json;charset=UTF-8")
	@ResponseBody
	public Object showApplyActivityStaticList(Page page) throws Exception{
		Map map = getRequestParameter(this.getRequest());
		map.put("type", 1);
		map.put("mpId", getLoginUser().getMpId());
		page.setMap(map);
		List<Map<String,Object>> list = custActivityApplyService.listPageActivityApplyStatic(page);
		return pagelistToJSONForBootStrapTable(list,page);
	}
	
	
	
	
	
	/**
	 * 跳转到报名统计选项页面
	 * @return
	 */
	@RequestMapping("/toShowApplyOption")
	public String toShowApplyOption(Integer id,String openId,Model model){
		if(StringUtils.isNotBlank(String.valueOf(id))&&StringUtils.isNotBlank(openId)){
			List<CustActivityApply> list = custActivityApplyService.selectCustActivityApplyOptionByActivityId(id,openId);
			model.addAttribute("applyList", list);
			return "activity/edit_apply_static";
		}else{
			return "redirect:activity/toApplyStaticPage";
		}
		
		
	}
	
	
	
	/**
	 * 删除报名统计记录
	 */
	@RequestMapping("/toDeleteActivityApplyStatic")
	@ResponseBody
	public String toDeleteActivityApplyStatic(Integer id){
		Map<String,Object> map=new HashMap<String, Object>();
		int i=0;
		if(null!=id){
			
			
			i = custActivityApplyService.deleteCustActivityApplyByActivityId(id);
			
		}
		if(i>0){
			map.put("status", 200);
			map.put("msg", "删除报名活动统计成功");
		}else{
			map.put("status", 400);
			map.put("msg", "删除报名活动统计失败");
		}
		return JsonUtils.objectToJson(map);
	}
	
	
	
	
//-------------帮助方法----------------------------------------------------------//	
	
	/**
	 * 获取富文本编辑器上传的图片
	 * @param request
	 * @return
	 */
	public File[] getPathImg(HttpServletRequest request){
		SimpleDateFormat formater = new SimpleDateFormat("yyyyMMddHHmm");
		String servletPath = "/umeditor/jsp/upload/"+formater.format(new Date());
		String realPath = request.getSession().getServletContext()
				.getRealPath(servletPath);
		File file = new File(realPath);
		File [] files = file.listFiles();
        return files;
	}
	
	
	
	/**
	 * 获取富文本编辑器上传的图片
	 * @param request
	 * @return
	 */
	public List<File> getPathImg(String path,HttpServletRequest request){
		String[] p=getImgaddress(path);
		SimpleDateFormat formater = new SimpleDateFormat("yyyyMMddHH");
		List<File> files = new ArrayList<File>();
		String servletPath = "/umeditor/jsp/upload/"+formater.format(new Date());
		if(p.length>0){
			for(int i=0;i<p.length;i++){
				String realPath = request.getSession().getServletContext()
						.getRealPath(servletPath);
				File file = new File(realPath+"/"+p[i]);
				System.out.println(file.getPath());
				files.add(file);
			}
		}
        return files;
	}
	
	/**
     * 返回存有图片地址的数组
     * @param tar
     * @return
     */
    public static String[] getImgaddress(String tar){
        List<String> imgList = getImg(tar);

        String res[] = new String[imgList.size()];

        if(imgList.size()>0){
            for (int i = 0; i < imgList.size(); i++) {
                int begin = imgList.get(i).indexOf("\"")+1;
                int end = imgList.get(i).lastIndexOf("\"");
                String url[] = imgList.get(i).substring(begin,end).split("/");
                res[i]=url[url.length-1];
            }
        }else{
        }
        return res;
    }
    
    public static List<String> getImg(String s)
    {
        String regex;
        List<String> list = new ArrayList<String>();
        regex = "src=\"(.*?)\"";
        Pattern pa = Pattern.compile(regex, Pattern.DOTALL);
        Matcher ma = pa.matcher(s);
        while (ma.find())
        {
            list.add(ma.group());
        }
        return list;
    }
    
    
 
	
}
